<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- icon -->

    <link
      rel="shortcut icon"
      href="https://images.cy-zq.cn/logo/Google/cy11.png"
      type="image/x-icon"
    />
    <title>CY</title>

    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "G-FQJ1Q67QZY", {
        page_path: window.location.pathname,
        page_location: window.location.href,
        page_title: document.title,
      });

      // 添加页面加载完成事件
      window.addEventListener("load", function () {
        gtag("event", "page_view");
      });
    </script>
    <!-- End Google Analytics -->

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/github-markdown-css/github-markdown.css"
    />

    <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it-footnote/3.0.3/markdown-it-footnote.min.js"></script>

    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-okaidia.min.css"
    />

    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/prism.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-sql.min.js"></script>

    <style>
      .markdown-body {
        box-sizing: border-box;
        min-width: 200px;
        max-width: 980px;
        margin: 0 auto;
        padding: 45px;
      }

      .markdown-body hr {
        border: none;
      }

      /* 代码块容器样式 */
      pre {
        position: relative !important;
      }

      /* 复制按钮样式 */
      .copy-btn {
        position: absolute;
        top: 5px;
        right: 5px;
        z-index: 10;
        padding: 4px 8px;
        color: white;
        font-size: 12px;
        background-color: rgba(68, 68, 68, 0.8);
        border: none;
        border-radius: 3px;
        cursor: pointer;
        opacity: 0;
        transition: all 0.2s ease;
      }

      pre:hover .copy-btn {
        opacity: 0.8;
      }

      .copy-btn:hover {
        background-color: #444;
        opacity: 1 !important;
      }

      /* 复制成功提示 */
      .copy-success {
        background-color: #4caf50 !important;
        opacity: 1 !important;
      }

      .status {
        position: fixed;
        top: 10px;
        right: 22px;
        z-index: 1001;
        padding: 10px;
        font-size: 14px;
        background: #f0f0f0;
        border-radius: 5px;
      }

      .input-container {
        position: fixed;
        bottom: 10px;
        left: 50%;
        z-index: 1000;
        width: 100vw;
        text-align: center;
        background: white;
        transform: translateX(-50%);
      }

      #input-container #input {
        background: rgb(243 244 246);
        resize: none;
      }

      #send {
        position: absolute;
        right: calc(50% - 35vw);
        bottom: 10px;
        width: 40px;
        border-radius: 5px;
        cursor: pointer;
      }

      .title {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1000;
        width: 100vw;
        padding: 12px;
        font-weight: 600;
        font-weight: 600;
        font-size: 16px;
        text-align: center;
        background: white;
      }
    </style>
  </head>

  <body>
    Ï
    <div class="title"></div>
    <div class="status" id="status"></div>
    <div class="input-container" id="input-container">
      <textarea
        id="input"
        placeholder="请输入问题"
        rows="2"
        style="
          width: 70vw;
          height: 70px;
          border: 1px solid #ccc;
          border-radius: 15px;
          padding: 8px;
        "
      ></textarea>
      <img
        id="send"
        src="https://chaoyang-oss.oss-cn-hangzhou.aliyuncs.com/%E5%8F%91%E9%80%81.png"
        alt=""
        onclick="fetchDeepseekStream(); "
      />
    </div>
    <div
      class="chat-container"
      style="height: calc(100vh - 130px); overflow-y: auto; position: relative"
    >
      <div id="output" class="markdown-body"></div>
    </div>

    <script>
      // 初始化markdown-it实例
      const mdUtils = window.markdownit().utils;
      const md = window
        .markdownit({
          highlight: function (str, lang) {
            if (lang && Prism.languages[lang]) {
              try {
                return (
                  '<pre class="language-' +
                  lang +
                  '"><code>' +
                  Prism.highlight(str, Prism.languages[lang], lang) +
                  "</code></pre>"
                );
              } catch (err) {}
            }
            return "<pre><code>" + mdUtils.escapeHtml(str) + "</code></pre>";
          },
        })
        .use(window.markdownitFootnote);

      let isUserScrolling = false;
      let autoScrollEnabled = true;

      const chatContainer = document.querySelector(".chat-container");

      // 自动滚动到底部
      function scrollToBottom() {
        if (autoScrollEnabled && !isUserScrolling) {
          chatContainer.scrollTop = chatContainer.scrollHeight;
        }
      }

      // 监听用户滚动
      chatContainer.addEventListener("scroll", () => {
        const { scrollTop, scrollHeight, clientHeight } = chatContainer;
        isUserScrolling = scrollTop + clientHeight < scrollHeight - 30;
      });

      // 监听内容变化
      const observer = new MutationObserver(scrollToBottom);
      observer.observe(chatContainer, {
        childList: true,
        subtree: true,
      });

      // 重新启用自动滚动
      chatContainer.addEventListener("wheel", () => {
        const { scrollTop, scrollHeight, clientHeight } = chatContainer;
        if (scrollTop + clientHeight >= scrollHeight - 30) {
          autoScrollEnabled = true;
        }
      });
    </script>
    <script>
      async function fetchDeepseekStream() {
        let question = document.getElementById("input").value;
        const url = encodeURI(
          "https://server.cy-zq.cn/api/openai/sql?quest=" + question
        );
        // let url1 = `http://localhost:8888/word`
        document.querySelector(".title").innerHTML = question;
        // 清空输入框，确保用户可以继续输入新的问题
        document.getElementById("input").value = "";
        const outputDiv = document.getElementById("output");
        const statusDiv = document.getElementById("status");
        let markdown = "";
        let startTime = Date.now();
        let charCount = 0;

        statusDiv.innerHTML = "开始请求...";

        try {
          const response = await fetch(url);

          const reader = response.body.getReader();
          const decoder = new TextDecoder("utf-8", { fatal: true });

          while (true) {
            const { value, done } = await reader.read();
            if (done) break;

            const text = decoder.decode(value, { stream: true });
            markdown += text;
            charCount += text.length;

            console.log(markdown);

            // 处理SQL语法高亮
            const formattedMarkdown = ensureSqlHighlighting(markdown);
            outputDiv.innerHTML = md.render(formattedMarkdown);

            // 为代码块添加复制按钮
            addCopyButtonsToCodeBlocks();

            const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
            statusDiv.innerHTML = `
                        已用时间：${elapsedTime}秒<br>
                        字符数：${charCount}
                    `;
          }

          const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
          statusDiv.innerHTML += `<br>完成！总用时：${totalTime}秒`;
        } catch (error) {
          console.error("请求错误:", error);
          statusDiv.innerHTML = "请求出错！";
        }
      }

      // 为所有代码块添加复制按钮
      function addCopyButtonsToCodeBlocks() {
        const codeBlocks = document.querySelectorAll("pre");

        codeBlocks.forEach((codeBlock) => {
          // 避免重复添加按钮
          if (codeBlock.querySelector(".copy-btn")) return;

          // 创建复制按钮
          const copyButton = document.createElement("button");
          copyButton.className = "copy-btn";
          copyButton.textContent = "复制";
          copyButton.addEventListener("click", function () {
            const codeText = codeBlock.querySelector("code").innerText;

            // 使用clipboard API复制文本
            navigator.clipboard
              .writeText(codeText)
              .then(() => {
                // 显示复制成功
                copyButton.classList.add("copy-success");
                copyButton.textContent = "已复制";

                // 2秒后恢复按钮状态
                setTimeout(() => {
                  copyButton.classList.remove("copy-success");
                  copyButton.textContent = "复制";
                }, 2000);
              })
              .catch((err) => {
                console.error("复制失败:", err);
                copyButton.textContent = "复制失败";

                // 2秒后恢复按钮状态
                setTimeout(() => {
                  copyButton.textContent = "复制";
                }, 2000);
              });
          });

          // 直接添加到pre元素中
          codeBlock.style.position = "relative";
          codeBlock.appendChild(copyButton);
        });
      }

      // 确保SQL语法块被正确高亮
      function ensureSqlHighlighting(text) {
        // 检测未被标记为sql的SQL代码块
        const sqlPatterns = [
          /SELECT\s+.*\s+FROM\s+\w+/i,
          /INSERT\s+INTO\s+\w+/i,
          /UPDATE\s+\w+\s+SET/i,
          /DELETE\s+FROM\s+\w+/i,
          /CREATE\s+TABLE/i,
          /ALTER\s+TABLE/i,
          /DROP\s+TABLE/i,
          /JOIN\s+\w+\s+ON/i,
        ];

        // 查找可能的代码块
        let lines = text.split("\n");
        let inCodeBlock = false;
        let codeBlockType = "";
        let result = [];

        for (let i = 0; i < lines.length; i++) {
          const line = lines[i];

          // 检测代码块开始和结束
          if (line.trim().startsWith("```")) {
            if (!inCodeBlock) {
              // 代码块开始
              inCodeBlock = true;
              codeBlockType = line.trim().substring(3).trim();

              // 如果没有指定语言且内容看起来像SQL
              if (!codeBlockType && i + 1 < lines.length) {
                const nextLine = lines[i + 1].trim();
                if (sqlPatterns.some((pattern) => pattern.test(nextLine))) {
                  result.push("```sql");
                  continue;
                }
              }
            } else {
              // 代码块结束
              inCodeBlock = false;
              codeBlockType = "";
            }
          }

          result.push(line);
        }

        return result.join("\n");
      }

      const textarea = document.getElementById("input");
      // 监听键盘按下事件
      textarea.addEventListener("keydown", (event) => {
        // 检查是否按下 Enter 键（keyCode 13 或 key 'Enter'）
        if (event.key === "Enter" || event.keyCode === 13) {
          // 阻止默认换行行为（可选）
          event.preventDefault();

          // 获取输入内容
          const text = textarea.value.trim();

          // 如果内容不为空，执行操作
          if (text) {
            // 执行你想要的操作，比如发送请求或处理文本
            fetchDeepseekStream();

            // 清空输入框（可选）
            textarea.value = "";
          }
        }
      });
    </script>
  </body>
</html>
